package com.zw.yzk.kabu.presenter;

import android.support.v7.app.AppCompatActivity;

import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.base.BaseSubscriber;
import com.zw.yzk.kabu.data.network.task.LoginTask;
import com.zw.yzk.kabu.domain.repository.UseCase;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.view.view.LoginView;

import javax.inject.Inject;

/**
 * Created by zhanwei on 2016/12/24.
 */

public class LoginPresenter implements Presenter {

    private UseCase login;
    private LoginView loginView;
    private AppCompatActivity activity;

    @Inject
    public LoginPresenter(UseCase login, AppCompatActivity appCompatActivity) {
        this.login = login;
        this.activity = appCompatActivity;
    }

    public void setView(LoginView view) {
        this.loginView = view;
    }

    public void login(String phone, String token) {
        login.execute(new LoginSubscriber(activity), new LoginTask(phone, token));
    }

    @Override
    public void resume() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {
        login.unSubscribe();
    }

    private class LoginSubscriber extends BaseSubscriber<Boolean> {

        LoginSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public void onNext(Boolean result) {
            super.onNext(result);
            if (result) {
                loginView.loginSuccess();
            } else {
                loginView.loginFail();
            }
        }

        @Override
        public void onCompleted() {
            super.onCompleted();
            LoadingDialogManager.getInstance().dismissLoadingDialog();
        }

        @Override
        public String addErrorMessage() {
            return activity.getResources().getString(R.string.login_fail);
        }
    }
}
